home *** CD-ROM | disk | FTP | other *** search
- Path: druid.borland.com!usenet
- From: pete@borland.com (Pete Becker)
- Newsgroups: comp.lang.c
- Subject: Re: char/int conversion and comparison
- Date: 23 Mar 1996 17:36:32 GMT
- Organization: Borland International
- Message-ID: <4j1cr0$dpc@druid.borland.com>
- References: <4j0234$7hi@nuscc.nus.sg>
- NNTP-Posting-Host: pbecker.borland.com
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=ISO-8859-1
- X-Newsreader: WinVN 0.99.5
-
- In article <4j0234$7hi@nuscc.nus.sg>, eng30403@leonis.nus.sg says...
- >
- > I got confused by the conversion and comparison between int and
- >char. Consider the following fragment of code :
- >
- > char foo1='a'; /* 1st line */
- > int foo2='a'; /* 2nd line */
- >
- > if (foo2==foo1); /* 3rd line */
- >
- > Is this comparison guaranteed to evaluate to TRUE on all machines ?
- >
- > I have read that on different machines, char may be implemented
- >as signed or unsigned. Hence if sizeof(int) > sizeof(char), a promotion
- >of char to int may or may not extend the most significant bit.
- >
-
- Correct. However, all characters in the source character set
- (A-Z,a-z,0-9,!=#%&'()*+,-./:;<=>?[\]^_{|}~) are guaranteed to be positive. So
- you don't have to worry about sign extension affecting 'a'. You do have to
- worry about it for something like '\xff'.
-
- > On the other hand, a conversion of int to char, (if sizeof(int) >
- >sizeof(char) ) results in the more significant bits being truncated. In
- >line 1 above, the int 'a' is truncated and converted to a char foo1.
- >Subsequently, the char foo1 is promoted to an int in the comparison with
- >foo2.
- >
-
- Yup. But this shouldn't affect the value. That is,
-
- char ch = X;
- int i = ch;
- char ch1 = i;
-
- ch1 will compare equal to ch.
-
- > Since we cant tell whether the sign bit is extended or not, is it
- >wise to use such a comparison if we want to be portable ?
-
- The problem, as I indicated earlier, arises when you go outside the source
- character set, and then only if you perform some operation on the character
- that you are dealing with. You may be surprised by the result if you don't pay
- enough attention to sign extension.
- Incidentally, you can tell whether char is signed or unsigned, which in
- turn tells you whether promotions to int will result in sign extension. The
- header limits.h defines the macros SCHAR_MIN, SCHAR_MAX, UCHAR_MIN, UCHAR_MAX,
- CHAR_MIN, and CHAR_MAX. CHAR_MIN and CHAR_MAX will hold values that are
- identical to the values of SCHAR_MIN and SCHAR_MAX if chars are signed, or
- values that are identical to the values of UCHAR_MIN and UCHAR_MAX if chars are
- unsigned.
- -- Pete
-
-